//
//  CPAudioPlayerView.m
//  GHTestWebViewDemo
//
//  Created by collegepre on 16/12/2.
//  Copyright © 2016年 张冠华. All rights reserved.
//

#import "CPAudioPlayerView.h"
//#import "UIView+CP.h"
#import <AVFoundation/AVFoundation.h>


@interface CPAudioPlayerView ()
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UILabel *contentTimeLabel;

@property (nonatomic, strong) CPAudioPlayer *audioPlayer;

@property (weak, nonatomic) IBOutlet UILabel *currentTImeLabel;


@property (nonatomic, strong) NSTimer *progressTimer;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *currenttimeLabel;

@property (nonatomic, assign) BOOL  isSliderPlay;

@property (nonatomic, strong) UIView *superView;

@property (weak, nonatomic) IBOutlet UIButton *dragBtn2;
@property (weak, nonatomic) IBOutlet UIButton *dragBtn1;
@end

@implementation CPAudioPlayerView

- (double)audioPlayProgress{
    if (self.audioPath && self.audioPlayer) {
        return self.audioPlayer.player.currentTime / self.audioPlayer.player.duration;
    }else{
        return 0.0f;
    }
}


- (NSTimer *)progressTimer{
    if (!_progressTimer) {
        _progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(refreshProgressView) userInfo:nil repeats:YES];
    }
    return _progressTimer;
}

- (CPAudioPlayer *)audioPlayer{
    if (!_audioPlayer) {
        _audioPlayer = [[CPAudioPlayer alloc] init];
        
    }
    return _audioPlayer;
}

// 初始化
+ (instancetype)audioPlayerView{
    
    CPAudioPlayerView *playerView = [[[NSBundle bundleForClass:[CPAudioPlayerView class]] loadNibNamed:@"CPAudioPlayerView" owner:nil options:nil] lastObject];
    
    playerView.dragBtn1.hidden = YES;
    playerView.dragBtn2.hidden = YES;
    
    playerView.progressSlider.value = 0;
    playerView.progressSlider.minimumTrackTintColor = [CPAudioTools audio_colorWithHexString:@"#cccccc"];
    playerView.progressSlider.maximumTrackTintColor = [CPAudioTools audio_colorWithHexString:@"#666666"];
    playerView.layer.cornerRadius = 15;
    
    playerView.clipsToBounds = YES;
    
    playerView.currentTImeLabel.textColor = [CPAudioTools audio_colorWithHexString:@"#85c0ec"];
    playerView.contentTimeLabel.textColor = [UIColor darkGrayColor];
    
    playerView.currentTImeLabel.font = [UIFont systemFontOfSize:15];
    playerView.contentTimeLabel.font = [UIFont systemFontOfSize:15];
    
    // [playerView.progressSlider setThumbImage:[UIImage imageNamed:@"drag"] forState:UIControlStateNormal];
    [playerView.progressSlider setMinimumTrackImage:[UIImage imageNamed:@"l_loading"] forState:UIControlStateNormal];
    [playerView.progressSlider setMaximumTrackImage:[UIImage imageNamed:@"s_loading"] forState:UIControlStateNormal];
    
    return playerView;
}

- (instancetype)audioPlayerViewWithSuperView:(UIView *)superView{
    
    self.frame = CGRectMake((1024 - 390)/ 2, 768 - 76, 390, 76);
    [superView addSubview:self];
    
    self.dragBtn1.hidden = NO;
    self.dragBtn2.hidden = NO;
    
    self.superView = superView;
    UIPanGestureRecognizer *pangets1 = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAudioPlayerView1:)];
    UIPanGestureRecognizer *pangets2 = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAudioPlayerView1:)];
    
    [self.dragBtn1 addGestureRecognizer:pangets1];
    [self.dragBtn2 addGestureRecognizer:pangets2];
    return self;
}

// 拖拽音频播放器
- (void)panAudioPlayerView1:(UIPanGestureRecognizer *)pangets{
    
    CGPoint translation = [pangets translationInView:pangets.view];
    CGFloat Y = translation.y;
    CGFloat X = translation.x;
    
    [UIView animateWithDuration:0.1 animations:^{
        if (self.center.x >= 0 && self.center.x <= 1024) {
            CGPoint center = self.center;
            center.x += X;
            self.center = center;
        }else if(self.center.x >1024){
            CGPoint center = self.center;
            center.x = 1024;
            self.center = center;
            
        }else{
            CGPoint center = self.center;
            center.x = 0;
            self.center = center;
        }
        
        if ( self.center.y >= 0 &&self.center.y <= 768) {
            CGPoint center = self.center;
            center.y += Y;
            self.center = center;
            
        }else if(self.center.y >768){
            
            CGPoint center = self.center;
            center.y = 768;
            self.center = center;
        }else{
            CGPoint center = self.center;
            center.y = 0;
            self.center = center;
        }
    }];
    
    [pangets setTranslation:CGPointZero inView:pangets.view];
}

// 拖拽音频播放器
- (void)panAudioPlayerView2:(UIPanGestureRecognizer *)pangets{
    
    CGPoint translation = [pangets translationInView:pangets.view];
    CGFloat Y = translation.y;
    CGFloat X = translation.x;
    
    [UIView animateWithDuration:0.1 animations:^{
        if (self.center.x >= 0 && self.center.x <= 1024) {
            CGPoint center = self.center;
            center.x += X;
            self.center = center;
        }else if(self.center.x >1024){
            CGPoint center = self.center;
            center.x = 1024;
            self.center = center;
            
        }else{
            CGPoint center = self.center;
            center.x = 0;
            self.center = center;
        }
        
        if ( self.center.y >= 0 &&self.center.y <= 768) {
            CGPoint center = self.center;
            center.y += Y;
            self.center = center;
            
        }else if(self.center.y >768){
            
            CGPoint center = self.center;
            center.y = 768;
            self.center = center;
        }else{
            CGPoint center = self.center;
            center.y = 0;
            self.center = center;
        }
    }];
    
    [pangets setTranslation:CGPointZero inView:pangets.view];
}


- (void)awakeFromNib{
    [super awakeFromNib];
}


- (IBAction)progressSiliderDragEnter:(UISlider *)sender {
    //    NSLog(@"progressSiliderDragEnter");
}

- (IBAction)progressSliderDragExit:(UISlider *)sender {
    //    NSLog(@"progressSliderDragExit");
    
}
- (IBAction)progressSliderValueChange:(UISlider *)sender {
    //    NSLog(@"progressSliderValueChange");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.duration * sender.value];
    });
}

// 开始拖拽
- (IBAction)touchDown:(UISlider *)sender {
    //    NSLog(@"touchDown");
    
    self.isSliderPlay = self.playBtn.selected;
    
    [self puasePlayAuidoWhenDragSlider];
}
- (IBAction)touchCancel:(UISlider *)sender{
    //    NSLog(@"touchCancel");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}
- (IBAction)touchDownRepeat:(UISlider *)sender {
    //    NSLog(@"touchDownRepeat");
}

// 拖拽中
- (IBAction)touchDargInside:(UISlider *)sender {
    //    NSLog(@"touchDargInside");
    
    [self puasePlayAuido];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.duration * sender.value];
    });
}
- (IBAction)touchDragOutSide:(UISlider *)sender {
    //    NSLog(@"touchDragOutSide");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}

// 拖拽结束结束
- (IBAction)touchupInside:(UISlider *)sender {
    //    NSLog(@"touchupInside");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}


- (IBAction)touchupOutSide:(UISlider *)sender  {
    //    NSLog(@"touchupOutSide");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}

- (void)setAudioPlayProgress:(double)progress audioPlayState:(BOOL)isPlay{
    self.audioPlayer.player.currentTime = progress * self.audioPlayer.player.duration;
    if (isPlay) {
        [self continuePlayAudio];
    }else{
        [self puasePlayAuido];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressSlider.value = progress;
        self.contentTimeLabel.text = [NSString stringWithFormat:@"/ %@",[self timeWithSeconds:self.audioPlayer.player.duration]] ;
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
    });
    
}


- (void)puasePlayAuido{
    [self.audioPlayer pausePlaying];
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    
    self.playBtn.selected = NO;
    
}

- (void)puasePlayAuidoWhenDragSlider{
    [self.audioPlayer pausePlaying];
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    
    
    
}

- (void)continuePlayAudio{
    [self.audioPlayer continuePlaying];
    
    [self.progressTimer fire];
    
    self.playBtn.selected = YES;
}

- (void)stopPlayAudio{
    if (self.audioPlayer.isPlaying)
    {
        [self.audioPlayer stopPlaying];
        [self.progressTimer invalidate];
        self.progressTimer = nil;
        
        
    }
    self.progressSlider.value = 0.0f;
    
    self.playBtn.selected = NO;
}

- (void)cancelpressProgressbtn{
    
    if (self.audioPlayer.isPausePlaying) {
        float progress = self.progressSlider.value;
        self.audioPlayer.player.currentTime = self.audioPlayer.player.duration * progress;
        [self.audioPlayer continuePlaying];
        
        [self.progressTimer fire];
    }
    
}

// 开始播放
- (void)startPlayWithAudioPath:(NSString *)path complition:(CPAudioPlayerComplitionBlock)complition{
    self.playBtn.selected = YES;
    if ([self.audioPath isEqualToString:path]) {
        [self continuePlayAudio];
    }else{
        
        BOOL isExit = [[NSFileManager defaultManager] fileExistsAtPath:path];
        if(isExit){
            [self.audioPlayer stopPlaying];
            
            self.audioPath = path;
            [self.audioPlayer startPlayingWithName:path block:^{
                [self.progressTimer invalidate];
                self.progressTimer = nil;
                
                self.progressSlider.value = 0.0f;
                self.currentTImeLabel.text = @"00:00";
                
                self.playBtn.selected = NO;
                self.complitionBlock();
                complition();
                
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.contentTimeLabel.text = [NSString stringWithFormat:@"/ %@",[self timeWithSeconds:self.audioPlayer.player.duration]] ;
                self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
            });
            
            [self.progressTimer fire];
        }else{
            NSLog(@"audio文件不存在");
            self.playBtn.selected = NO;
            if (self.complitionBlock) {
                self.complitionBlock();
            }
            
            complition();
        }
    }
}


- (void)refreshProgressView{
    float progress = self.audioPlayer.player.currentTime / self.audioPlayer.player.duration;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressSlider.value = progress;
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
    });
}


// 点击播放按钮
- (IBAction)playBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        if (self.audioPath && ![self.audioPath isEqualToString:@""]) {
            [self.audioPlayer continuePlaying];
            [self.progressTimer fire];
        }else{
            sender.selected = NO;
        }
    }else{
        [self.audioPlayer pausePlaying];
        
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
    
    // 回调状态
    self.playBlock(self.audioPlayer.player.currentTime,sender.isSelected);
}

- (NSString *)timeWithSeconds:(NSTimeInterval)seconds{
    NSInteger mints = seconds / 60;
    NSInteger secs = (NSInteger)seconds % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld",(long)mints,(long)secs];
}
- (IBAction)closeBtnClick:(id)sender {
    [self.audioPlayer stopPlaying];
    if (self.closeBlock) {
        self.closeBlock();
    }
}



@end
